package com.wei.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.stream.IntStream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wei.model.MapConfig;

import lombok.extern.log4j.Log4j;

@Log4j
public class MapConfigLoader {

	private static final String CONFIG_NAME = "config.properties";
	public static final String RECODE_NAME = "record.txt";
	
	private static MapConfigLoader configLoader = new MapConfigLoader();
	
	private static Properties properties = null;
	
	private static boolean isLoadConfig = false;
	
	private static MapConfig mapConfig = new MapConfig();
	
	private static void loadConfig(){
		InputStream in = null;
		InputStream in2 = null;
		BufferedReader bf = null;
		try {
			ClassLoader loader = MapConfigLoader.class.getClassLoader();
			properties = new Properties();
			in = loader.getResourceAsStream(CONFIG_NAME);
			bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
			properties.load(bf);
			mapConfig.setExtent(configLoader.getDoubleArr("map.extent"));
			mapConfig.setImageStragePath(configLoader.getValue("image.strage.path", null));
			mapConfig.setOffsetZoom(configLoader.getValueInt("map.offsetZoom"));
			mapConfig.setOrigin(configLoader.getDoubleArr("map.origin"));
			mapConfig.setResolutions(configLoader.getDoubleArr("map.resolutions"));
			mapConfig.setTaskThreadCount(configLoader.getValueInt("task.thread.count"));
			mapConfig.setTileSize(configLoader.getIntArr("map.tileSize"));
			mapConfig.setIndexStrageCycle(configLoader.getValueInt("index.strage.cycle"));
			mapConfig.setFailUrlPath(configLoader.getValue("fail.url.path", null));
			
			in2 = loader.getResourceAsStream(RECODE_NAME);
			if(in2 != null) {
				byte[] b = new byte[1024];
				int len = -1;
				StringBuffer sb = new StringBuffer();
				while ((len = in2.read(b)) > -1) {
					sb.append(new String(b, 0, len));
				}
				JSONObject json = JSON.parseObject(sb.toString());
				mapConfig.setIndex(json != null ? json.getIntValue("index"):0);
				mapConfig.setZoom(json != null ? json.getIntValue("zoom"):0);
			}else {
				String path = MapConfigLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
				if(path.endsWith(".jar")) {
					path = path.substring(0, path.lastIndexOf(File.separatorChar));
				}
				path = path + File.separatorChar + RECODE_NAME;
				log.info("path:"+path);
				boolean flag = new File(path).createNewFile();
				log.info(path+"文件不存在，自动创建! " + flag);
			}
		} catch (FileNotFoundException e) {
			log.error(CONFIG_NAME+"file not found!",e);
		} catch (Exception e) {
			log.error(CONFIG_NAME+"load exception!",e);
		} finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in2 != null){
				try {
					in2.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bf != null) {
				try {
					bf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private static void doLoadConfig(){
		if(isLoadConfig){
			return;
		}
		synchronized (CONFIG_NAME) {
			if(!isLoadConfig)
				loadConfig();
			isLoadConfig = true;
		}
	}
	
	public static MapConfigLoader getInstance(){
		doLoadConfig();
		return configLoader;
	}
	
	public MapConfig getMapConfig() {
		return mapConfig;
	}
	
	public double[] getDoubleArr(String key) {
		String value = this.getValue(key, null);
		value = value.replaceAll(" ", "");
		String[] arr = value.split(",");
		double[] result = new double[arr.length];
		IntStream.range(0, arr.length).forEach(idx -> {
			result[idx] = Double.parseDouble(arr[idx]);
		});
		return result;
	}
	
	public int[] getIntArr(String key) {
		String value = this.getValue(key, null);
		value = value.replaceAll(" ", "");
		String[] arr = value.split(",");
		int[] result = new int[arr.length];
		IntStream.range(0, arr.length).forEach(idx -> {
			result[idx] = Integer.parseInt(arr[idx]);
		});
		return result;
	}
	
	public int getValueInt(String key){
		return Integer.parseInt(this.getValue(key, "-1"));
	}
	
	public String getValue(String key,String defaultValue){
		if(properties == null){
			return defaultValue;
		}
		Object value = properties.get(key);
		String valueStr = String.valueOf(value);
		if(value == null || valueStr.trim().length() == 0){
			return defaultValue;
		}
		return valueStr;
	}
	
	public static void main(String[] args) {
		
		MapConfig config = MapConfigLoader.getInstance().getMapConfig();
		System.out.println(config);
	}
}
